const response = require('../../utils/response');
const { handleDatabaseError } = require('../../utils/dberrordeal');
const AddressService = require('../../services/good/addressService');
class AddressController {
    static async getAddressList(ctx) {
        const { pageNum = 1, pageSize = 10 } = ctx.request.body;
        const data = ctx.request.body || {};
        data.userId = ctx.userId;
        const res = await AddressService.getAddressList({ pageNum, pageSize }, data);
        res ? response.success(ctx, { data: res }) : response.error(ctx, {});
    }

    static async getAddressById(ctx) {
        const { id: addressId } = ctx.request.body;
        const res = await AddressService.getAddressById(addressId);
        res ? response.success(ctx, { data: res }) : response.error(ctx, { message: '地址不存在'});
    }

    static async createAddress(ctx) {
        const addressData = ctx.request.body;
        addressData.userId = ctx.userId;
        await AddressService.createAddress(addressData)
            .then(() => response.success(ctx, {}))
            .catch(err => handleDatabaseError(ctx, err, '地址名称重复'));
    }

    static async updateAddress(ctx) {
        const addressData = ctx.request.body;
        await AddressService.updateAddress(addressData.id, addressData)
            .then(() => response.success(ctx, {}))
            .catch(err => handleDatabaseError(ctx, err, '地址名称重复'));
    }

    static async deleteAddress(ctx) {
        const { id: addressId } = ctx.request.body;
        const res = await AddressService.deleteAddress(addressId);
        res ? response.success(ctx, {}) : response.error(ctx, {});
    }
}
module.exports = AddressController;